<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.prop === 'invoiceType'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
              Select(v-if="item.prop === 'serverName'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'radio'")
              RadioGroup.beautiful-radio-group(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="(c_item, index) of item.radioArr" :key="index" :label="c_item.label") {{c_item.label}}
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval(:value="formData[item.model1]" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker(item.model1, $event)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval(:value="formData[item.model2]" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker(item.model2, $event)")
            template(v-if="item.type === 'button'")
              Button(v-if="hasFind" type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.font-14(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
              Divider(type="vertical")
              |已开具
              span.text-info.pl-5.pr-5.font-weight {{tableComone.yesCount}}
              |条
              Divider(type="vertical")
              |未开具
              span.text-error.pl-5.pr-5.font-weight {{tableComone.noCount}}
              |条
          template(slot-scope="{ row, index }" slot="action")
            Button(v-if="hasPostInvoiceApply" type="text" @click="handleShowInvoiceWriteModal(row)") 发票信息填写
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )

    //- 发票信息填写弹窗
    InvoiceWriteModal(ref="InvoiceWriteModal" :arrListDown="arrListDown" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { InvoiceApi } from '@/api/Invoice.api.js'
import { ReceivableBillApi } from '@/api/ReceivableBill.api.js'
import { EnumApi } from '@/api/Enum.api.js'
import { InvoiceWriteThead } from './IAtableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import InvoiceWriteModal from './modal/invoiceWriteModalModal.vue'
// import CustomerSalaryDetailModal from './modal/customerSalaryDetailModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'invoiceApplication', // 发票申请页面

  components: {
    InvoiceWriteModal
    // CustomerSalaryDetailModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(InvoiceWriteThead),
      tableData: [],
      formData: {
        companyName: '',
        companyCode: '',
        companyLegalName: '',
        startDate: new Date(),
        endDate: new Date(),
        status: '',
        invoiceType: '',
        serverName: ''
      },
      formItem: [
        { type: 'input', label: '客户名称：', placeholder: '请输入客户名称', prop: 'companyName', model: 'companyName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'input', label: '客户编码：', placeholder: '请输入客户编码', prop: 'companyCode', model: 'companyCode', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'input', label: '客户法定名称：', placeholder: '请输入客户法定名称', prop: 'companyLegalName', model: 'companyLegalName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        // {type: 'select', label: '开票状态', placeholder: '请选择开票状态', prop: 'status', model: 'status', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', options: 'server'},
        { type: 'select', label: '发票类型：', placeholder: '请选择发票类型', prop: 'invoiceType', model: 'invoiceType', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', options: 'invoicetype' },
        { type: 'select', label: '所属客服：', placeholder: '请选择所属客服', prop: 'serverName', model: 'serverName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', options: 'server' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'startDate', model1: 'startDate', placeholder2: '结束日期', prop2: 'endDate', model2: 'endDate', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'radio', label: '开票状态：', placeholder: '请选择开票状态', prop: 'status', model: 'status', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', radioArr: [{ value: '', label: '全部' }, { value: '1', label: '已开具' }, { value: '0', label: '未开具' }] },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        yesCount: 0, // 已开具
        noCount: 0 // 未开具
      },
      downLoadRul: '',
      arrListDown: {
        invoiceitem: [],
        invoicetype: [],
        server: [],
        invoiceRate: [{ label: '0%', value: '0%' }, { label: '5%', value: '5%' }, { label: '6%', value: '6%' }]
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      }
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 发票信息填写
    hasPostInvoiceApply () {
      return this.actionArr.indexOf('PostInvoiceApply') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    }
  },
  watch: {
    '$route': 'initPage'
  },

  mounted () {
    this.getEnum()
    this.initPage()
    this.servers()
  },

  methods: {
    initPage () {
      if (this.$route.params.FilterType) {
        this.formData.status = '未开具'
      } else {
        this.formData.status = ''
      }
      this.query()
    },
    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    // 数据字典
    getEnum () {
      let groupName = 'invoice.invoiceitem,invoice.invoicetype'
      Common.getEnum(groupName, this.arrListDown)
      // console.log('数据字典：', this.arrListDown)
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await InvoiceApi.getApplyInvoiceList({ ...params, ...this.formData })
      console.log('发票res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.yesCount = res.data.yesCount
        this.tableComone.noCount = res.data.noCount
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ' + model + ', val: ', val)
      this.formData[model] = val
      // this.getDayList()
    },

    // 导出员工数据
    async exportEmployees () {
      console.log('formInvoice: ', this.formInvoice)
      let res = await EmployeesApi.exportEmployees(this.formInvoice)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      }
    },

    // 到款填写
    goReceivePaymentCreate (companyId, companyCode, companyName, periodYear, periodMonth) {
      this.$router.push({
        path: '/ReceivePaymentCreate',
        name: 'ReceivePaymentCreate',
        query: {
          companyId: companyId,
          companyName: companyName,
          companyCode: companyCode,
          year: periodYear,
          month: periodMonth
        }
      })
    },

    // 显示弹窗-发票信息填写
    handleShowInvoiceWriteModal (row) {
      this.$refs.InvoiceWriteModal.show()
      Object.keys(this.$refs.InvoiceWriteModal.formData).forEach(key => {
        if (key !== 'taxNumber' && key !== 'invoiceType' && key !== 'createTime') {
          this.$refs.InvoiceWriteModal.formData[key] = row[key] || ''
        } else {
        }
      })
      console.log('🐟🐟🐟', this.$refs.InvoiceWriteModal.formData)
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
